extends Node

@onready var terrain = $"../Terrain"

var foodPrototypes = []

var itemsInWorld = []

var itemCategories = ["Item", "Food", "Weapon", "MeleeWeapon", "ProjectileWeapon"]

enum ItemCategory {
	ITEM = 0,
	FOOD = 1,
	WEAPON = 2,
	MELEEWEAPON = 3,
	PROJECTILEWEAPON = 4,
}

func LoadFood():
	var path = "res://Item/Food"
	var dir = DirAccess.open(path)
	dir.open(path)
	dir.list_dir_begin()
	while true:
		var file_name = dir.get_next()
		if file_name == "":
			break
		elif file_name.ends_with(".tscn"):
			foodPrototypes.append(load(path +"/"+file_name))
			print(file_name)
	dir.list_dir_end()

func SpawnItem(item, mapPos):
	var newItem = item.instantiate()
	newItem.position = Map2WorldPosition(mapPos.x, mapPos.y)
	add_child(newItem)
	itemsInWorld.append(newItem)
	
func Map2WorldPosition(mapPosX: int, mapPosY: int) -> Vector2:
	var tileSize = terrain.rendering_quadrant_size
	return Vector2(mapPosX * tileSize + tileSize/2,  mapPosY * tileSize + tileSize/2)	
	
func FindNearestItem(itemCategory: ItemCategory, worldPos: Vector2):
	if len(itemsInWorld) == 0:
		return false
	var nearestItem = null
	var nearestDistance = 99999
	for item in itemsInWorld:
		if IsItemInCategory(item, itemCategory):
			var distance = worldPos.distance_to(item.position)
			if nearestDistance == null or distance < nearestDistance:
				nearestDistance = distance
				nearestItem = item
	return nearestItem
	
func IsItemInCategory(item, itemCategory) -> bool:
	return item.is_in_group(itemCategories[itemCategory])
	
		
# Called when the node enters the scene tree for the first time.
func _ready():
	LoadFood()
	
	SpawnItem(foodPrototypes[0], Vector2(5, 10))
	SpawnItem(foodPrototypes[1], Vector2(10, 8))
	SpawnItem(foodPrototypes[1], Vector2(5, 12))
	SpawnItem(foodPrototypes[0], Vector2(10, 10))
	
	#print(IsItemInCategory(itemsInWorld[0], ItemCategory.FOOD))
	#print(IsItemInCategory(itemsInWorld[0], ItemCategory.ITEM))
	#print(IsItemInCategory(itemsInWorld[0], ItemCategory.WEAPON))


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	pass
